package com.lhfeiyu.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.config.Assets;
import com.lhfeiyu.config.Const;
import com.lhfeiyu.config.Tip;
import com.lhfeiyu.config.base.BaseAssets;
import com.lhfeiyu.config.base.BaseConst;
import com.lhfeiyu.config.base.BaseTip;
import com.lhfeiyu.dao.AuctionGoodsMapper;
import com.lhfeiyu.dao.AuctionInstMapper;
import com.lhfeiyu.dao.AuctionProfessionMapper;
import com.lhfeiyu.dao.AuctionProfessionOffersMapper;
import com.lhfeiyu.dao.AuctionUserMapper;
import com.lhfeiyu.dao.base.BaseChatMapper;
import com.lhfeiyu.dao.base.BaseGoodsMapper;
import com.lhfeiyu.dao.base.BaseNoticeMapper;
import com.lhfeiyu.dao.base.BaseOrderGoodsMapper;
import com.lhfeiyu.dao.base.BaseOrderInfoMapper;
import com.lhfeiyu.dao.base.BaseSchedulersMapper;
import com.lhfeiyu.dao.base.BaseShopMapper;
import com.lhfeiyu.dao.base.BaseUserMapper;
import com.lhfeiyu.domain.base.AliyunOSS;
import com.lhfeiyu.domain.base.YtxMessage;
import com.lhfeiyu.po.AuctionGoods;
import com.lhfeiyu.po.AuctionInst;
import com.lhfeiyu.po.AuctionProfession;
import com.lhfeiyu.po.AuctionUser;
import com.lhfeiyu.po.base.BaseGoods;
import com.lhfeiyu.po.base.BaseNotice;
import com.lhfeiyu.po.base.BaseOrderGoods;
import com.lhfeiyu.po.base.BaseOrderInfo;
import com.lhfeiyu.po.base.BaseSchedulers;
import com.lhfeiyu.po.base.BaseUser;
import com.lhfeiyu.po.base.BaseUserFund;
import com.lhfeiyu.service.base.BaseCommonFundService;
import com.lhfeiyu.service.base.BasePictureService;
import com.lhfeiyu.service.base.CommonService;
import com.lhfeiyu.tools.YTX_MessageTool;
import com.lhfeiyu.tools.base.Check;
import com.lhfeiyu.tools.base.CommonGenerator;
import com.lhfeiyu.tools.base.DateFormat;
import com.lhfeiyu.tools.base.Result;
import com.lhfeiyu.tools.base.WxMessageFactory;
import com.lhfeiyu.util.base.YTX_MSG;
import com.lhfeiyu.vo.base.ChatGroup;

@Service
public class AuctionProfessionService extends CommonService<AuctionProfession> {
	@Autowired
	AuctionProfessionMapper apMapper;
	@Autowired
	AuctionInstMapper aiMapper;
	@Autowired
	AuctionUserMapper auMapper;
	@Autowired
	AuctionGoodsMapper agMapper;
	@Autowired
	BaseGoodsMapper goodsMapper;
	@Autowired
	BaseChatMapper chatMapper;
	@Autowired
	BaseOrderInfoMapper orderInfoMapper;
	@Autowired
	BaseOrderGoodsMapper orderGoodsMapper;
	@Autowired
	BaseSchedulersMapper sMapper;
	@Autowired
	BaseNoticeMapper noticeMapper;
	@Autowired
	BaseShopMapper shopMapper;
	@Autowired
	BaseCommonFundService cfService;
	@Autowired
	ChatService chatService;
	@Autowired
	BasePictureService pictureService;
	@Autowired
	YTX_MessageTool ytx;
	@Autowired
	BaseUserMapper userMapper;
	@Autowired
	AuctionProfessionOffersMapper auctionProfessionOffersMapper;

	public JSONObject addOrUpdateAuctionProfession(JSONObject json, BaseUser user, AuctionProfession ap, String auctionGoodsAry, String basePath, String payPassword) {
		Map<String, Object> map = CommonGenerator.getHashMap();
		Integer apId = ap.getId();
		Integer userId = user.getId();
		boolean moneyFlag = false;// 暂固定为无推广红包
		/*
		 * 一期暂不考虑红包推广 BigDecimal money = ap.getSpreadPackets(); boolean
		 * moneyFlag = false; if(null != money && money.doubleValue() > 0){
		 * if(!Check.isNotNull(payPassword)){ json.put("status", "failure");
		 * json.put("msg", "您设置了推广红包，将会冻结推广红包金额，请填写支付密码"); return
		 * Result.success(json); } moneyFlag = true; }
		 */
		// 诚信保证金不再保存到店铺表中，而是保存到用户资金表中的otherFund
		/*
		 * map.put("userId", userId); BaseShop shop =
		 * shopMapper.selectByCondition(map); map.clear(); if(null == shop){
		 * return Result.failure(json, BaseTip.msg_shop_null,
		 * BaseTip.code_shop_null); } user.setShopId(shop.getId());
		 */
		// 相同代码：AuctionMicroAction-addAuctionMicroOffer，AuctionMicroService-addUpdateAuctionMicro
		// AuctionProfessionAction-addOrUpdateAuctionProfession
		if (null != ap.getTypeId() && ap.getTypeId() == 2) {
			ap.setBail(new BigDecimal(1000));// TODO 暂时固定为1000，应该从数据库中读取
			BigDecimal bailBD = ap.getBail();
			if (null != bailBD && bailBD.doubleValue() > 0) {
				BaseUserFund uf = cfService.selectUserFundByUserId(userId);
				BigDecimal creditMoney = uf.getOtherFund();
				// Integer creditMoney = shop.getCreditMargin();
				if (null == creditMoney || creditMoney.doubleValue() <= 0) {// 诚信保证金为空
					json.put("creditMoneyLack", bailBD.doubleValue());
					json.put("bail", bailBD.doubleValue());
					return Result.failure(json, BaseTip.msg_creditMoney_null, BaseTip.code_creditMoney_null);
				} else if (creditMoney.doubleValue() < bailBD.doubleValue()) {// 诚信保证金不足
					String tip = BaseTip.msg_creditMoney_lack.replace("@money@", creditMoney.toString());
					Double moneyLack = bailBD.doubleValue() - creditMoney.doubleValue();
					json.put("moneyLack", moneyLack);
					json.put("creditMoney", creditMoney.doubleValue());
					json.put("bail", bailBD.doubleValue());
					return Result.failure(json, tip, BaseTip.code_creditMoney_lack);
				}
			}
		}
		AuctionInst ai = aiMapper.selectByCondition(map);
		if (null == ai) {
			return Result.failure(json, "您尚未开通专场，无法发布专场拍卖", "auctionInst_null");
		}
		ap.setInstId(ai.getId());// 拍卖设置所属机构

		String picServerId = ap.getPicServerId();

		//System.out.println("AuctionProfessionService:addOrUpdateAuctionProfession:picServerId: " + picServerId);

		if (Check.isNotNull(ap.getOssPicPath())) {// 页面上已经将微信图片转换为了oss图片
			ap.setPicPaths(ap.getOssPicPath());
		} else {
			if (Check.isNotNull(picServerId)) {// 从微信服务器获取图片
				String endpoint = Const.oss_endpoint;
				String accessKeyId = Const.oss_accessKeyId;
				String accessKeySecret = Const.oss_accessKeySecret;
				String bucketName = Const.oss_bucketName;
				String bucketEndpoint = Const.oss_bucketEndpoint;
				AliyunOSS oss = AliyunOSS.buildOSS(null, null, endpoint, accessKeyId, accessKeySecret, bucketName, bucketEndpoint);

				json = pictureService.getPicPathsByWxServerIds(json, picServerId, basePath, oss);
				String picPaths = json.getString("picPaths");
				if (Check.isNotNull(picPaths)) {
					if (picPaths.startsWith(","))
						picPaths = picPaths.substring(1);
					int index = picPaths.lastIndexOf(",");
					if (index > 0)
						picPaths = picPaths.substring(index, picPaths.length());
					ap.setPicPaths(picPaths);
				}
			} else if (Check.isNull(ap.getPicPaths())) {
				ap.setPicPaths(Assets.defaultAuctionBanner);
			}
		}
		if (null == apId) {// 添加
			json = checkProfession(ap, json);
			if (Result.hasError(json)) {
				return json;
			}
			/*
			 * 不限制添加 map.put("userId", userId); map.put("notOver",
			 * 1);//检查有无还没结束的拍卖 Integer count =
			 * apService.selectCountByCondition(map); if(Check.isGtZero(count)){
			 * return Result.failure(json, "您还有未结束的拍卖，等拍卖结束后再添加吧",
			 * "auction_notOver"); }
			 */
			// TODO 拍卖添加成功后，冻结推广金额
			json = addAuctionProfession(user, ap, auctionGoodsAry, moneyFlag, payPassword, json);// 拍卖添加成功后，冻结推广金额
			return Result.success(json);
		} else {// 修改
			map.put("userId", userId);
			map.put("notOver", 1);// 检查有无还没结束的拍卖
			AuctionProfession dbAP = apMapper.selectByPrimaryKey(apId);
			if (null == dbAP) {
				return Result.failure(json, Tip.msg_auction_null, Tip.code_auction_null);
			}
			Integer haveBegun = dbAP.getHaveBegun();
			if (null != haveBegun) {
				if (haveBegun == 3) {
					return Result.failure(json, Tip.msg_auctionUpdate_over, Tip.code_auctionUpdate_over);
				}
				if (haveBegun == 2) {
					return Result.failure(json, Tip.msg_auctionUpdate_ing, Tip.code_auctionUpdate_ing);
				}
			}
			json = checkProfession(ap, json);
			if (Result.hasError(json)) {
				return json;
			}
			AuctionProfession newAP = new AuctionProfession();
			newAP.setId(apId);
			newAP.setAuctionName(ap.getAuctionName());
			newAP.setBail(ap.getBail());
			// newAP.setSpreadPackets(ap.getSpreadPackets());//暂不支持推广金额
			newAP.setPicPaths(ap.getPicPaths());
			newAP.setStartTime(ap.getStartTime());
			newAP.setUpdatedAt(new Date());
			newAP.setUpdatedBy(user.getUsername());

			/*
			 * BigDecimal dbMoney = dbAP.getSpreadPackets(); boolean dbMoneyFlag
			 * = true; if(null == dbMoney || dbMoney.doubleValue() <= 0){
			 * dbMoneyFlag = false; } boolean isUpdateMoney = true; if(moneyFlag
			 * || dbMoneyFlag){//推广金额不为空 冻结推广金额 double totalMoney = 0; boolean
			 * isAdd = true; if(moneyFlag && !dbMoneyFlag){//新增推广金额 totalMoney =
			 * money.doubleValue(); }else if(!moneyFlag && dbMoneyFlag){//删除推广金额
			 * totalMoney = dbMoney.doubleValue(); isAdd = false; }else
			 * if(moneyFlag && dbMoneyFlag){//改变推广金额 - 计算 double moneyD =
			 * money.doubleValue(); double dbMoneyD = dbMoney.doubleValue();
			 * if(moneyD > dbMoneyD){ totalMoney = moneyD - dbMoneyD; }else
			 * if(moneyD < dbMoneyD){ totalMoney = dbMoneyD - moneyD ; isAdd =
			 * false; }else if(moneyD == dbMoneyD){ isUpdateMoney = false; } }
			 * if(isUpdateMoney){ String linkUrl = "/as?r="+user.getSerial();
			 * if(isAdd){ //TODO 修改 //json = cfService.freezeMoney(payPassword,
			 * new BigDecimal(totalMoney), userId, user.getUsername(), 151,
			 * null, "平台冻结", json, false,linkUrl); }else{ //TODO 修改 //json =
			 * cfService.activateMoney(payPassword, new BigDecimal(totalMoney),
			 * userId, user.getUsername(), 151, null, "平台解冻", json,
			 * false,linkUrl); } } if(json.containsKey("error_desc")){ return
			 * Result.success(json); } }
			 */
			apMapper.updateByPrimaryKeySelective(newAP);
			if (Check.isNotNull(auctionGoodsAry)) {
				addOrUpdateAGList(json, user, null, auctionGoodsAry, apId, "replace");
			}
			json.put("apSerial", ap.getSerial());
		}
		return Result.success(json);
	}

	private JSONObject checkProfession(AuctionProfession ap, JSONObject json) {
		Integer instId = ap.getInstId();
		String auctionName = ap.getAuctionName();
		Date startDate = ap.getStartTime();
		if (null == instId) {
			return Result.failure(json, "所属专场不能为空", "auctionInst_null");
		}
		AuctionInst ai = aiMapper.selectByPrimaryKey(instId);
		if (null == ai) {
			return Result.failure(json, "该专场已不存在", "auctionInst_null");
		}
		if (null == auctionName || "".equals(auctionName)) {
			return Result.failure(json, "本次拍卖名称不能为空", "auctionName_null");
		}
		if (null == startDate || (new Date().after(startDate))) {
			return Result.failure(json, "拍卖开始日期不正确", "startDate_invalid");
		}
		return json;
	}

	public JSONObject addAuctionProfession(BaseUser user, AuctionProfession ap, String auctionGoodsAry, boolean moneyFlag, String payPassword, JSONObject json) {
		Date date = new Date();
		Integer userId = user.getId();
		String username = user.getUsername();
		ChatGroup group = new ChatGroup();// 新增一场拍卖，就新增一个群组
		group.setGroupName(ap.getAuctionName());
		group.setPermission("0");
		group.setType("2");
		group.setThirdName(Const.rl_ytx_default_subAccount);// 换为应用登陆
		group.setThirdPassword(Const.rl_ytx_default_password);
		// String groupId = ChatGroupService.createGroup(group);

		String groupId = "gg8008953840";// TODO FIXME
										// 临时测试··························································································································································

		if (Check.isNull(groupId)) {
			groupId = ChatGroupService.createGroup(group);
		}
		if (Check.isNull(groupId)) {
			return Result.failure(json, "本场拍卖添加失败:群组创建失败", "ap_group_create_failure");
		}
		// String groupId = "123";//测试时不真实添加群组
		ap.setChatGroupId(groupId);
		String serial = CommonGenerator.getSerialByDate(Assets.serial_prefix_auctionProfession);
		// String auctionSerial = serial.replace("ap", "");
		// ap.setAuctionSerial(auctionSerial);
		ap.setSerial(serial);
		ap.setEndTime(null);
		ap.setHaveBegun(4);// 是否已经开始（1否，2是，3结束，4未提交，5提交审核中）
		ap.setHaveNoticed(1);
		ap.setJoinNum(1);
		ap.setVisitNum(1);
		ap.setMainStatus(1);
		ap.setDeletedAt(null);
		ap.setDeletedBy(null);
		ap.setCreatedAt(date);
		ap.setCreatedBy(username);
		ap.setUserId(userId);
		ap.setShopId(user.getShopId());
		apMapper.insert(ap);
		Integer apId = ap.getId();
		if (null == apId) {
			apMapper.insert(ap);
			apId = ap.getId();
		}
		if (null == apId) {
			return Result.failure(json, "本场拍卖添加失败，请重新重新添加", "ap_add_failure");
		}
		if (Check.isNotNull(auctionGoodsAry)) {
			addOrUpdateAGList(json, user, null, auctionGoodsAry, apId, "replace");
		}

		// 更新拍场编号：在id的基础上加123
		Integer auctionSerial = apId + 123;
		ap.setAuctionSerial("" + auctionSerial);
		ap.setUpdatedBy(username);
		apMapper.updateByPrimaryKeySelective(ap);

		// json.put("apId", apId);
		json.put("apSerial", serial);
		json.put("auctionSerial", auctionSerial);
		/*
		 * if (moneyFlag) {// 推广金额不为空 冻结推广金额 - 暂不支持推广金额 String linkUrl =
		 * "/as?r=" + user.getSerial(); // TODO 修改 // json =
		 * cfService.freezeMoney(payPassword, ap.getSpreadPackets(), // userId,
		 * user.getUsername(), 151, null, "平台冻结", json, // false,linkUrl); if
		 * (json.containsKey("error_desc")) { return json; } }
		 */
		return json;
	}

	public JSONObject addOrUpdateAGList(JSONObject json, BaseUser user, List<AuctionGoods> agList, String auctionGoodsAry, Integer professionId, String opt) {
		if (null == agList) {
			agList = JSONArray.parseArray(auctionGoodsAry, AuctionGoods.class);
		}
		String incomeGoodsIds = "";
		for (AuctionGoods ag : agList) {
			Integer goodsId = ag.getGoodsId();
			incomeGoodsIds += "," + goodsId;
		}
		Map<String, Object> map = CommonGenerator.getHashMap();
		map.put("auctionId", professionId);
		String ids = agMapper.selectGoodsIdsOfProfession(map);
		if (Check.isNotNull(ids)) {// 修改时先将已经添加的产品状态改为默认状态（1）
			map.clear();
			map.put("goodsIds", ids);
			map.put("mainStatus", 1);
			map.put("updatdAt", new Date());
			map.put("updatedBy", user.getUsername());
			goodsMapper.updateStatusByIds(map);
			String condition = null;
			if (Check.isNotNull(opt)) {
				if (Check.isNotNull(incomeGoodsIds))
					incomeGoodsIds = incomeGoodsIds.substring(1);
				if ("del".equals(opt)) {// 如果是删除，删除后就直接返回
					condition = "(goods_id IN (" + incomeGoodsIds + ")) AND auction_id=" + professionId;
					agMapper.deleteByCondition(condition);
					return json;
				} else if ("add".equals(opt)) {// 添加，先去重，再添加
					condition = "(goods_id IN (" + incomeGoodsIds + ")) AND auction_id=" + professionId;
				} else if ("replace".equals(opt)) {// 全部替换
					condition = "(main_status IS NULL OR main_status=1) AND auction_id=" + professionId;
				}
			}
			if (Check.isNotNull(condition)) {
				agMapper.deleteByCondition(condition);
			}
		}
		agList = resetList(agList, user, professionId);
		if (Check.isNotNull(agList)) {
			agMapper.insertBatch(agList);
		}
		return json;
	}

	private List<AuctionGoods> resetList(List<AuctionGoods> agList, BaseUser user, Integer professionId) {
		List<AuctionGoods> newAGList = new ArrayList<AuctionGoods>();
		String goodsIds = "";
		Date date = new Date();
		Integer userId = user.getId();
		String username = user.getUsername();
		// int index = 1;
		// String serial = "";
		for (AuctionGoods ag : agList) {
			Integer goodsId = ag.getGoodsId();
			if (null == goodsId)
				continue;
			BaseGoods dbGoods = goodsMapper.selectByPrimaryKey(goodsId);
			if (null == dbGoods)
				continue;
			// Integer status = dbGoods.getMainStatus();
			// if ((null != status && status != 1 && status != 76) || (null !=
			// dbGoods.getModuleId() && dbGoods.getModuleId() == 5))continue;//
			// 只能添加非批发城中正在出售的藏品
			// int dbUserId = dbGoods.getUserId();
			// int toUserId = userId;
			// if(dbUserId != toUserId)continue;//该商品不属于当前用户，不预添加
			AuctionGoods newAG = new AuctionGoods();
			/*
			 * BigDecimal pb = ag.getPriceBegin(); if (null == pb) {
			 * newAG.setPriceBegin(new BigDecimal(0)); } else {
			 * newAG.setPriceBegin(ag.getPriceBegin()); }
			 */
			/*
			 * String mediaId = ag.getPicPath(); if(Check.isNotNull(mediaId) &&
			 * !mediaId.equalsIgnoreCase("undefined")){ String basePath =
			 * request.getServletContext().getRealPath("/"); String picOSSUrl =
			 * ImgFromUrl.saveImgFromUrl(basePath, mediaId,
			 * null);//图片存放服务器的路径，可直接新增入数据库中 //System.out.println(
			 * "addOrUpdateGoods:filePath - "+picOSSUrl); //String localPath =
			 * "/file/wx/" + picOSSUrl.substring(picOSSUrl.lastIndexOf("/"),
			 * picOSSUrl.length()); //newAG.setLocalPicPath(localPath);
			 * //newAG.setOssPicPath(picOSSUrl); newAG.setPicPath(picOSSUrl);
			 * 
			 * String filePath = ImgFromUrl.saveImgFromUrl(mediaId,
			 * null);//图片存放服务器的路径，可直接新增入数据库中 //System.out.println(
			 * "addOrUpdateAuctionProfession - "+filePath);
			 * newAG.setPicPath(filePath); }
			 */
			/*
			 * newAG.setPicPath(dbGoods.getPicPath()); newAG.setUserId(userId);
			 * newAG.setAuctionId(professionId);
			 * newAG.setGoodsId(ag.getGoodsId()); newAG.setMainStatus(1);
			 * newAG.setCreatedAt(date); newAG.setCreatedBy(username);
			 */

			newAG.setUserId(userId);
			newAG.setAuctionId(professionId);
			newAG.setGoodsId(dbGoods.getId());
			newAG.setGoodsSerial(dbGoods.getSerial());
			newAG.setPriceBegin(dbGoods.getAuctionPrice());// 这里读取goods表中的auction_price起拍价
			newAG.setPostageFee(dbGoods.getPostageFee());
			newAG.setScansCount(1);
			newAG.setSerial(CommonGenerator.getSerialByDate(Assets.serial_prefix_auctionGoods));
			newAG.setMainStatus(1);
			newAG.setCreatedAt(date);
			newAG.setCreatedBy(username);

			/*
			 * if (index < 10) { serial = "00" + index; } else if (index < 100)
			 * { serial = "0" + index; } newAG.setGoodsSerial(serial); index++;
			 */
			newAGList.add(newAG);
			goodsIds += "," + goodsId;
		}
		if (goodsIds.length() > 0) {
			goodsIds = goodsIds.substring(1);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("goodsIds", goodsIds);
			map.put("mainStatus", 71);// 专场拍卖中
			map.put("updatdAt", date);
			map.put("updatedBy", username);
			goodsMapper.updateStatusByIds(map);// 更新商品拍卖状态
		}
		return newAGList;
	}

	public int updateJoinNumAdd(Map<String, Object> map) {
		return apMapper.updateJoinNumAdd(map);
	}

	public int updateVisitNumAdd(Map<String, Object> map) {
		return apMapper.updateVisitNumAdd(map);
	}

	public void updateProfessionGoodsOneDone() {
		String professionIds = apMapper.selectAlreadyBegin();
		// //System.out.println("AuctionJob_selectAlreadyBegin_professionIds"+professionIds);
		if (Check.isNull(professionIds))
			return;
		String[] idAry = professionIds.split(",");
		Map<String, Object> map = new HashMap<String, Object>();
		// map.put("auctionType", 1);//1:专场
		for (String apId : idAry) {
			int professionId = Integer.parseInt(apId);
			map.put("professionId", professionId);
			int updateCount = agMapper.updateStatusByRefresh(map);// 返回更新的拍品状态的条数，如果有值，则更新下一个拍品的refresh_time
			// //System.out.println("AuctionJob_professionId"+professionId+"
			// ,updateCount"+updateCount);
			if (updateCount <= 0)
				continue;
			int haveFirst = agMapper.updateFirstRefresh(map);// 更新下一个拍品的refresh_time，若没有值，则拍品已经拍卖完毕，更新专场表的拍卖状态
			// //System.out.println("AuctionJob_professionId"+professionId+"
			// ,haveFirst"+haveFirst);
			if (haveFirst <= 0) {
				// apMapper.updateAuctionOver(map);//拍卖结束
				updateAuctionOver(map, professionId);
			}
		}
	}

	private void updateAuctionOver(Map<String, Object> map, int professionId) {
		Date date = new Date();
		apMapper.updateAuctionOver(map);// 拍卖结束
		// TODO 将流拍的拍品的状态改为普通状态（非拍卖状态）
		map.clear();
		map.put("auctionId", professionId);
		String goodsIds = agMapper.selectGoodsIdsDoneButNotDeal(map);
		if (null != goodsIds && !"".equals(goodsIds)) {
			map.put("mainStatus", 1);// 普通状态
			map.put("updatedAt", date);
			map.put("updatedBy", "-SYS-");
			map.put("goodsIds", goodsIds);
			goodsMapper.updateStatusByIds(map);
		}

		// TODO 计算推广拍场收益
		AuctionProfession ap = apMapper.selectByPrimaryKey(professionId);
		BigDecimal promteMoney = ap.getSpreadPackets();
		if (null == promteMoney || promteMoney.doubleValue() <= 0)
			return; // 如果没有推广红包就直接退出
		double money = promteMoney.doubleValue();
		if (money <= 0)
			return;
		map.clear();
		// Integer userId = null;
		// String username = null;
		// BaseUserFund uf = null;
		map.put("auctionType", 1);// 专场
		map.put("auctionId", professionId);
		map.put("mainStatusNotDone", 1);// 获取没有计算收益的数据
		JSONObject json = new JSONObject();
		String inviteUserIds = auMapper.selectAuctionInviteUserIds(map);
		if (null != inviteUserIds && inviteUserIds.length() > 0) {
			String[] idAry = inviteUserIds.split(",");
			int length = idAry.length;
			double eachMoney = money / length;
			if (eachMoney > 10)
				eachMoney = 10;// 单个提成最多为10元
			if (eachMoney < 0.01)
				eachMoney = 0.01;// 单个提成最少为0.01元

			for (String inviteUserId : idAry) {
				if (money <= 0)
					break;// 钱已扣完就退出
				map.put("inviteUserId", inviteUserId);
				List<AuctionUser> auList = auMapper.selectListByCondition(map);
				if (Check.isNotNull(auList)) {
					int size = auList.size();
					double totalMoney = eachMoney * size;
					if (money <= totalMoney)
						totalMoney = money;
					money -= totalMoney;

					// AuctionUser au = auList.get(0);//
					// 只用取第一条数据（推广人为同一人，专场管理人也为同一人）
					// Integer ivtUserId = au.getInviteUserId();
					// String ivtUsername = au.getInviteUsername();
					// userId = au.getAuctionManagerId();
					// username = au.getAuctionManagerName();
					// uf = cfService.selectUserFundByUserId(userId);
					json.clear();
					// TODO 修改
					// json =
					// cfService.outcomeFrozenMoneyToUserAvaliable(uf.getPayPassword(),
					// new BigDecimal(totalMoney),
					// userId, username, 149, ivtUserId, ivtUsername, json,
					// false, null);
					// TODO 新增淘客收入到distributionIncome表中 - 淘客后期开发
					/*
					 * DistributionIncome di = new DistributionIncome();
					 * di.setTypeId(132);// 推广拍场 di.setUserId(ivtUserId);
					 * di.setObjectName(username); di.setCustomerId(userId);
					 * di.setAuctionId(professionId); di.setDealTime(date);
					 * di.setMoneyIncome(new BigDecimal(totalMoney));
					 * di.setMainStatus(1); di.setCreatedAt(date);
					 * di.setCreatedBy("-SYS-"); diMapper.insert(di);
					 */
				}
			}
			if (money > 0) {// 如果钱未扣完，则返还给用户
				// outcomeFrozenMoney
				// TODO 修改
				// cfService.activateMoney(uf.getPayPassword(), new
				// BigDecimal(money), userId, username, 150, null,
				// "推广红包返还", json, false, null);
			}
		}
	}
	/*
	 * // 自动出价（委托出价）:在用户设置自动竞价的时候，先比较是否为最高价，若不是就不用保存到自动竞价表 public void
	 * checkAutoOffer() { List<AuctionGoods> agList =
	 * agMapper.selectProfessionGoodsAutoOffer(); if (null != agList &&
	 * agList.size() > 0) { for (AuctionGoods ag : agList) { pushAutoOffer(ag);
	 * } } }
	 * 
	 * public void pushAutoOffer(AuctionGoods ag) { String chatGroupId =
	 * ag.getChatGroupId(); if (null == chatGroupId || "".equals(chatGroupId))
	 * return; Double newOfferPrice = calculateNewPrice(ag);// 计算出最新出价
	 * 
	 * Integer userId = ag.getAutoUserId(); String username =
	 * ag.getAutoUsername(); Date date = new Date(); String dateStr =
	 * String.valueOf(date.getTime()); // String timeStamp = new //
	 * SimpleDateFormat("yyyyMMddHHmmss").format(date); String msgGroup =
	 * "msg_price"; String msgContent = "出价" + newOfferPrice + "元"; String
	 * goodsId = String.valueOf(ag.getGoodsId()); String newOfferPriceStr =
	 * String.valueOf(newOfferPrice); String userIdStr = String.valueOf(userId);
	 * String param = createMsg(newOfferPriceStr, userIdStr, username,
	 * ag.getSubAccount(), chatGroupId, dateStr, goodsId, msgGroup, msgContent);
	 * 
	 * //String r = chatService.doPush(json, user, param, date);
	 * //System.out.println(r);
	 * 
	 * AuctionGoods auctionGoods = new AuctionGoods();// 更新出价
	 * auctionGoods.setId(ag.getId()); auctionGoods.setUpdatedAt(date);
	 * auctionGoods.setOfferUserId(userId);
	 * auctionGoods.setOfferUsername(username); auctionGoods.setOfferPrice(new
	 * BigDecimal(newOfferPrice)); Integer offerTimes = ag.getOfferTimes(); if
	 * (null == offerTimes) offerTimes = 0;
	 * auctionGoods.setOfferTimes(++offerTimes);
	 * auctionGoods.setUpdatedBy(username); auctionGoods.setRefreshTime(new
	 * Date());// 倒计时的刷新时间 agMapper.updateByPrimaryKeySelective(auctionGoods);
	 * 
	 * BaseChat chat = new BaseChat();// 新增群组消息记录 chat.setTypeId(2);
	 * chat.setSenderId(userId); chat.setChatGroupId(chatGroupId);
	 * chat.setMsgGroup(msgGroup); chat.setContentType(1);
	 * chat.setContent(msgContent); chat.setCreatedAt(date);
	 * chat.setCreatedBy(username); chatMapper.insertSelective(chat);// 新增群组消息记录
	 * 
	 * }
	 * 
	 * private Double calculateNewPrice(AuctionGoods ag) { Double topPrice =
	 * ag.getAutoTopPrice().doubleValue();// 自动竞价的最高价 Double currentPrice =
	 * ag.getOfferPrice().doubleValue();// 当前出价 Double priceBegin =
	 * ag.getPriceBegin().doubleValue();// 起拍价 if (currentPrice < priceBegin)
	 * currentPrice = priceBegin; int priceGap = 10;// 加价跨度 if (currentPrice <=
	 * 50) { priceGap = 10; } else if (currentPrice < 400) { priceGap = 20; }
	 * else if (currentPrice < 1000) { priceGap = 50; } else { priceGap = 100; }
	 * Double newOfferPrice = currentPrice + priceGap; if (newOfferPrice >
	 * topPrice || newOfferPrice <= currentPrice) newOfferPrice = topPrice;
	 * return newOfferPrice; }
	 * 
	 * private String createMsg(String newOfferPrice, String userId, String
	 * username, String senderTokenId, String chatGroupId, String dateStr,
	 * String goodsId, String msgGroup, String msgContent) { ChatMsgDomain
	 * domain = new ChatMsgDomain(); domain.setAvatar("");
	 * domain.setName(username); domain.setUserId(String.valueOf(userId));
	 * domain.setReceiverId(chatGroupId); domain.setSingleOrGroup("2");
	 * domain.setSerial(dateStr); domain.setMsgGroup(msgGroup); String price =
	 * newOfferPrice; domain.setPrice(price);
	 * domain.setOfferPrice(newOfferPrice); domain.setAuctionGoodsId(goodsId);
	 * 
	 * ChatMsg msg = new ChatMsg(); String[] receiver = { chatGroupId };//
	 * 接收者账号，如果是个人，最大上限100人/次，如果是群组，仅支持1个。
	 * 
	 * msg.setMsgContent(msgContent); msg.setMsgDomain(domain.toJSONString());//
	 * domain.toJSONString() msg.setPushType("2");// 推送类型，1：个人，2：群组，默认为1
	 * msg.setReceiver(receiver); msg.setSender(Const.rl_ytx_default_voip); //
	 * msg.setSender(senderTokenId);//发送人ID msg.setMsgType("1");
	 * msg.setSerial(dateStr); String param = msg.toJSONString(); return param;
	 * }
	 */

	public void checkProfessionGoodsAddOrder() {// 新增订单
		JSONObject json = new JSONObject();
		List<AuctionGoods> agList = agMapper.selectOrderSnNull();
		if (Check.isNull(agList))
			return;
		Map<String, Object> map = new HashMap<String, Object>();
		for (AuctionGoods ag : agList) {
			json.clear();
			BigDecimal priceBD = ag.getOfferPrice();
			if (null == priceBD)
				continue;
			priceBD = priceBD.setScale(2, BigDecimal.ROUND_HALF_UP);// 设置保留两位小数
			double price = priceBD.doubleValue();
			if (price <= 0 || price >= 1000000)
				continue;
			Integer managerId = ag.getUserId();
			// String username = ag.getUsername();
			Integer goodsId = ag.getGoodsId();// 商品id
			if (null == managerId)
				continue;
			// 先扣除扣手续费 - 先从流动资金中扣除，如果不足则从冻解资金中扣除
			// TODO 修改
			/*
			 * double fee = 0; double scale =
			 * sysDictService.getProfessionDealFeeScale(); if (scale > 0) { fee
			 * = priceBD.doubleValue() * scale; if (fee > 0) { BigDecimal feeBD
			 * = new BigDecimal(fee); feeBD = feeBD.setScale(2,
			 * BigDecimal.ROUND_HALF_UP);// 设置保留两位小数 json =
			 * cfService.outcomeMoney("", feeBD, managerId, username, 155, null,
			 * "平台", json, true, getLinkUrl(goodsId)); if
			 * (json.containsKey("error_desc")) {
			 * cfService.outcomeFrozenMoney("", feeBD, managerId, username, 155,
			 * null, "平台", json, true, getLinkUrl(goodsId)); if
			 * (json.containsKey("error_desc")) { continue; } }
			 * sysDictService.incomeMoney(feeBD, 3, json); } }
			 */
			Integer userId = ag.getOfferUserId();
			Date date = new Date();
			String serial = CommonGenerator.getSerialByDate(BaseAssets.serial_prefix_orderInfo);
			BaseOrderInfo order = new BaseOrderInfo();
			order.setUsername(ag.getReceiverName());
			order.setProvince(ag.getProvince());
			order.setCity(ag.getCity());
			order.setAddress(ag.getAddressDetail());
			order.setPhone(ag.getPhone());
			order.setEmail(ag.getEmail());
			order.setOrderSn(serial);
			order.setSerial(serial);
			order.setUserId(userId);
			order.setOrderStatusCode(BaseConst.order_status_todo); // 数据字典代码-订单状态：未完成
			order.setShippingStatusCode(BaseConst.shipping_status_todo);// 数据字典代码-商品配送情况：未发货
			order.setPayStatusCode(BaseConst.pay_status_todo); // 数据字典代码-支付状态：未付款
			order.setOrderDoneStausCode(BaseConst.order_done_status_no);// 数据字典代码-订单完成状态：未完成
			order.setMainStatus(1);// 状态（1未结束订单，2已结束订单，3无效订单）
			order.setCreatedAt(date);
			order.setCreatedBy(BaseConst.operater_system);
			orderInfoMapper.insert(order);// 新增订单
			Integer orderId = order.getId();

			BaseOrderGoods og = new BaseOrderGoods();// 新增orderGoods
			og.setOrderId(orderId);
			// og.setGoodsId(ag.getGoodsId());
			og.setGoodsId(goodsId);
			og.setGoodsName(ag.getGoodsName());
			og.setGoodsSn(ag.getGoodsSn());
			og.setGoodsType(1);// 商品类型（1普通商品，2批发城商品）
			og.setGoodsFrom(3);// 商品来源（1批发城，2店铺，3专场，4微拍，5即时拍）
			og.setGoodsNumber(1);
			og.setShopPrice(priceBD);
			og.setMainStatus(1);
			og.setCreatedAt(date);
			og.setCreatedBy(BaseConst.operater_system);
			orderGoodsMapper.insertSelective(og);

			BaseGoods goods = new BaseGoods();// 更新goods状态
			// goods.setId(ag.getGoodsId());
			goods.setId(goodsId);
			goods.setMainStatus(78);// dict78:冻结中
			goods.setUpdatedAt(date);
			goods.setUpdatedBy("-SYS-");
			goodsMapper.updateByPrimaryKeySelective(goods);
			BaseGoods db_goods = goodsMapper.selectByPrimaryKey(goodsId);
			// withholdFee();//扣手续费 - 商品确认收货后再收取手续费

			// double price = ag.getOfferPrice().doubleValue();
			String content = "【" + db_goods.getGoodsName() + "】恭喜您竞拍成功（价格：" + price + "元），系统已经为您生成订单，可以到个人中心查看订单并付款";
			/*
			 * Dict dict = dictMapper.selectByPrimaryKey(20);//竞拍成功通知 if(null !=
			 * dict){ content = dict.getDictValue(); title = dict.getDictName();
			 * }
			 */
			map.clear();
			map.put("id", ag.getId());
			map.put("orderSn", serial);
			agMapper.updateOrderSn(map);
			BaseNotice notice = new BaseNotice();
			notice.setSerial(CommonGenerator.getSerialByDate("n"));
			notice.setReceiverId(userId);
			notice.setContent(content);
			notice.setReadStatus(1);// 未阅读
			notice.setTypeId(20);// 竞拍成功通知
			notice.setTitle(content);
			notice.setCreatedAt(date);
			notice.setCreatedBy("-SYS-");
			noticeMapper.insert(notice);// 新增通知

			String openId = ag.getUserOpenId();
			// 微信消息通知

			// //System.out.println("*********checkProfessionGoodsAddOrder****************");

			WxMessageFactory.bidSuccess(openId, goods.getGoodsName(), String.valueOf(price));
		}
	}

	public void updateCheckProfessionBegin() {
		String professionIds = apMapper.selectPrepareBegin();
		// //System.out.println("NoticeJob_selectPrepareBegin_professionIds"+professionIds);
		if (null != professionIds && professionIds.length() > 0) {
			String[] idAry = professionIds.split(",");
			Map<String, Object> map = new HashMap<String, Object>();
			// map.put("auctionType", 1);//1:专场
			for (String apId : idAry) {
				int professionId = Integer.parseInt(apId);
				map.put("professionId", professionId);
				agMapper.updateFirstRefresh(map);
			}
			// 将拍场更新为已开始状态
			map.clear();
			map.put("haveBegun", 2);// haveBegun:1未开始，2已开始，3已结束
			map.put("ids", professionIds);
			apMapper.updateHaveBegun(map);
		}
	}
	
	public void updateCheckProfessionNotice() {
		List<AuctionProfession> apList = apMapper.selectBeginApproach();
		//System.out.println("apList:"+apList.size());
		if (null != apList && apList.size() > 0) {
			Map<String, Object> map = new HashMap<String, Object>();
			String ids = "";
			for (AuctionProfession ap : apList) {
				map.clear();
				ids += "," + ap.getId();
				String auctionName = ap.getAuctionName();
				auctionName = "专场-" + auctionName;
			/*	map.put("professionId", ap.getId());
				map.put("noticeId", 1);// 通知ID(1专场开拍提醒)
*/
				map.clear();
				// map.put("auctionId", ap.getId());
				Date endTime = ap.getStartTime();
				Date now = new Date();
				if (null != endTime && endTime.after(now)) {// 如果结束时间为空或在当前时间之后，则还不应该设置为结束
					Date endTimeBefor = new Date(endTime.getTime() - (10 * 60 * 1000));
					if (now.before(endTime) && now.after(endTimeBefor)) {// 如果结束时间为空或在当前时间之后，则还不应该设置为结束
						BaseUser user = userMapper.selectByPrimaryKey(ap.getUserId());
						/* 信息推送到主持人 */
						YtxMessage ytxs = new YtxMessage();
						ytxs.setPhones(user.getPhone());
						ytxs.setParams(new String[] { auctionName });
						ytxs.setMobanId(Const.rl_ytx_msg_moban_notice_id);
						ytxs.setIp(Const.rl_ytx_ip);
						ytxs.setPort(Const.rl_ytx_port);
						ytxs.setSid(Const.rl_ytx_sid);
						ytxs.setAppId(Const.rl_ytx_appId);
						ytxs.setAuthToken(Const.rl_ytx_authToken);
						//YTX_MSG.send(ytxs);
//						WxMessageFactory.auctionMicroOver(user.getWxOpenid(), "您本次主持的拍卖将在10分钟后开始！", ap.getAuctionSerial(), auctionName,
//								"本场拍卖开始时间：" + DateFormat.format(ap.getStartTime(), DateFormat.minutesSdf));
						map.clear();
//						ids = ids.substring(1);
						/*map.put("ids", ids);
						apMapper.updateHaveNoticed(map);// 将拍场更新为已通知状态*/
						
						/* 推送到订阅人 */
						map.put("noticeId", "1");
						map.put("linkId", ap.getId());
						int count = sMapper.selectNoticeUserCount(map);
						//System.out.println("count" + count);
						if (count <= 0){
							ids = ids.substring(1);
							map.put("ids", ids);
							apMapper.updateHaveNoticed(map);// 将拍场更新为已通知状态	
							continue;
						}
						ytx.sendMsgByCount(map, count, auctionName);// 暂时不发短信
						List<BaseSchedulers> schedulers = sMapper.selectListByCondition(map);
						for (BaseSchedulers baseSchedulers : schedulers) {
							System.out.println("****");
							BaseUser users = userMapper.selectByPrimaryKey(baseSchedulers.getUserId());
							WxMessageFactory.auctionMicroOver(users.getWxOpenid(), "您订阅的拍卖将在10分钟后开始！", ap.getAuctionSerial(), auctionName,
									"本场拍卖开始时间：" + DateFormat.format(ap.getStartTime(), DateFormat.minutesSdf));
						}
						map.clear();
						ids = ids.substring(1);
						map.put("ids", ids);
						apMapper.updateHaveNoticed(map);// 将拍场更新为已通知状态	
					}
				}
			}
			// //System.out.println("NoticeJob_updateHaveNoticed_ids"+ids);
		}
	}

	public JSONObject doDelete(JSONObject json, BaseUser user, String serial) {
		if (Check.isNull(serial)) {
			return Result.failure(json, "拍卖场次编号不能为空", "apSerial_null");
		}
		AuctionProfession ap = apMapper.selectBySerial(serial);
		Integer userId = user.getId();
		Integer hostId = ap.getUserId();
		if (Check.integerNotEqual(userId, hostId)) {
			return Result.failure(json, "权限不足", "auth_lack");
		}
		Integer haveBegun = ap.getHaveBegun();
		Integer apId = ap.getId();
		if (null != haveBegun) {// 拍卖中
			if (haveBegun == 2) {
				return Result.failure(json, "本场拍卖正在拍卖中，无法删除", "ap_ing");
			} else if (haveBegun == 3) {// 已经拍卖结束的拍卖进行逻辑删除
				apMapper.updateDeletedNowById(apId, user.getUsername());
				return Result.success(json);
			}
		}
		agMapper.deleteByCondition("auction_id=" + apId);
		apMapper.deleteByPrimaryKey(apId);// 未开始或未提交的拍卖可直接删除
		return Result.success(json);
	}

	public JSONObject doSubmit(JSONObject json, BaseUser user, String serial) {
		if (Check.isNull(serial)) {
			return Result.failure(json, "拍卖场次编号不能为空", "apSerial_null");
		}
		AuctionProfession ap = apMapper.selectBySerial(serial);
		Integer userId = user.getId();
		Integer hostId = ap.getUserId();
		if (Check.integerNotEqual(userId, hostId)) {
			return Result.failure(json, "权限不足", "auth_lack");
		}
		Integer haveBegun = ap.getHaveBegun();
		Integer apId = ap.getId();
		if (null != haveBegun && haveBegun == 4) {// 是否已经开始（1否，2是，3结束，4未提交，5提交审核中）
			Map<String, Object> map = CommonGenerator.getHashMap();
			map.put("auctionId", apId);
			int agCount = agMapper.selectCountByCondition(map);
			if (agCount < 5) {
				return Result.failure(json, "拍品数量不足5件，无法提交审核", "agNum_lack");
			}
			map.put("haveBegun", 5);
			map.put("ids", apId);

			// DOTO FIXME 为方便初期测试，这里直接审核通过-后期需要修改
			map.put("haveBegun", 1);
			// DOTO FIXME 为方便初期测试，这里直接审核通过-后期需要修改

			apMapper.updateHaveBegun(map);
		} else {
			return Result.failure(json, "该场拍卖已经提交审核，不用重复提交", "submit_already");
		}
		return Result.success(json);
	}

	public List<AuctionProfession> selectBySchedulers(int userId) {
		// TODO Auto-generated method stub
		return apMapper.selectBySchedulers(userId);
	}

}
